import functools
import hashlib
import random


import pymysql

create_connection = functools.partial(
    pymysql.connect, host='127.0.0.1', port=3306,
    user='guest', password='123456', charset='utf8mb4'
)

THY_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ'


def random_pass(length, candidate_characters=THY_CHARS):
    """生成指定长度的随机密码"""
    return ''.join(random.choices(candidate_characters, k=length))


# class Person:
#
#     def __init__(self, name, age):
#         self.name = name
#         self.age = age
#
#
# p1 = Person('骆昊', 41)
# p2 = Person('王大锤', 18)
# print(getattr(p1, 'name', '无名氏'))
# print(getattr(p2, 'age', 0))
# print(getattr(p2, 'shit', None))


class NoSuchHashAlgorithmException(Exception):
    pass


def password_to_digest(password, *, hash_alg='md5'):
    """把密码变成指定的哈希摘要（指纹）"""
    cls = getattr(hashlib, hash_alg.lower(), None)
    if cls:
        hasher = cls(password.encode())
        return hasher.hexdigest()
    raise NoSuchHashAlgorithmException(f'没有{hash_alg}哈希算法')


if __name__ == '__main__':
    print(password_to_digest('123456'))
    print(password_to_digest('123456', hash_alg='sha256'))
    print(password_to_digest('123456', hash_alg='md7890'))
